package com.example.dictionary.service;

import com.example.dictionary.repository.WordEntryMapper;
import com.example.memento.model.DomainWord;
import com.example.memento.model.ExplanationEntry;
import com.example.memento.model.WordEntry;
import com.example.memento.model.WordModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 词典委托实现类
 * 基于 WordEntry 和 WordModel 的实现
 */
@Service("dictionaryDelegateImpl")
public class DictionaryDelegateImpl implements DictionaryDelegate {
    
    private static final Logger log = LoggerFactory.getLogger(DictionaryDelegateImpl.class);
    
    private final WordEntryMapper wordEntryMapper;
    
    // 用于内存缓存 WordModel（可选，如果不需要可以移除）
    // private final Map<String, WordModel> wordModelCache = new ConcurrentHashMap<>();
    
    public DictionaryDelegateImpl(WordEntryMapper wordEntryMapper) {
        this.wordEntryMapper = wordEntryMapper;
    }
    
    @Override
    public Optional<WordModel> findWord(String wordName) {
        if (wordName == null || wordName.trim().isEmpty()) {
            return Optional.empty();
        }
        
        String trimmedWord = wordName.trim();
        
        // 从数据库查询 WordEntry
        List<WordEntry> entries = wordEntryMapper.findByWord(trimmedWord);
        
        if (entries == null || entries.isEmpty()) {
            return Optional.empty();
        }
        
        // 将 WordEntry 转换为 WordModel
        WordModel wordModel = convertToWordModel(entries);
        
        return Optional.of(wordModel);
    }
    
    @Override
    public WordModel saveWord(WordModel wordModel) {
        if (wordModel == null) {
            throw new IllegalArgumentException("词汇对象不能为空");
        }
        
        // 确保主词名不为空
        if (wordModel.getPrimaryWord() == null || wordModel.getPrimaryWord().trim().isEmpty()) {
            // 尝试从完整词名列表中获取第一个
            if (wordModel.getFullWordNames() != null && !wordModel.getFullWordNames().isEmpty()) {
                wordModel.setPrimaryWord(wordModel.getFullWordNames().get(0));
            } else {
                throw new IllegalArgumentException("词汇对象必须有主词名或完整词名");
            }
        }
        
        // 将 WordModel 转换为 WordEntry 并保存
        List<WordEntry> entries = convertToWordEntries(wordModel);
        
        for (WordEntry entry : entries) {
            // 检查是否已存在
            List<WordEntry> existing = wordEntryMapper.findByWord(entry.getWord());
            boolean exists = existing.stream()
                    .anyMatch(e -> entry.getSource().equals(e.getSource()));
            
            if (exists) {
                // 更新现有记录
                WordEntry existingEntry = existing.stream()
                        .filter(e -> entry.getSource().equals(e.getSource()))
                        .findFirst()
                        .orElse(null);
                
                if (existingEntry != null) {
                    // 更新字段
                    updateWordEntry(existingEntry, entry);
                    entry.onUpdate();
                    wordEntryMapper.update(existingEntry);
                    log.debug("更新词条: {} (source: {})", entry.getWord(), entry.getSource());
                }
            } else {
                // 插入新记录
                entry.onCreate();
                wordEntryMapper.insert(entry);
                log.debug("插入新词条: {} (source: {})", entry.getWord(), entry.getSource());
            }
        }
        
        // 更新时间戳
        wordModel.onUpdate();
        
        log.info("保存词汇对象: {} ({} 个词条)", wordModel.getPrimaryWord(), entries.size());
        
        return wordModel;
    }
    
    @Override
    public boolean existsWord(String wordName) {
        if (wordName == null || wordName.trim().isEmpty()) {
            return false;
        }
        
        List<WordEntry> entries = wordEntryMapper.findByWord(wordName.trim());
        return entries != null && !entries.isEmpty();
    }
    
    /**
     * 将 WordEntry 列表转换为 WordModel
     */
    private WordModel convertToWordModel(List<WordEntry> entries) {
        if (entries == null || entries.isEmpty()) {
            return null;
        }
        
        WordModel wordModel = new WordModel();
        
        // 使用第一个 entry 的主信息
        WordEntry firstEntry = entries.get(0);
        wordModel.setPrimaryWord(firstEntry.getWord());
        wordModel.setLanguage(firstEntry.getLanguage());
        wordModel.setPartOfSpeech(firstEntry.getPartOfSpeech());
        wordModel.setFrequency(firstEntry.getFrequency());
        wordModel.setConfidence(firstEntry.getConfidence());
        
        // 添加完整词名（如果有多个不同的词名）
        List<String> fullWordNames = entries.stream()
                .map(WordEntry::getWord)
                .distinct()
                .collect(Collectors.toList());
        wordModel.setFullWordNames(fullWordNames);
        
        // 根据 source 分组，创建 DomainWord
        entries.stream()
                .collect(Collectors.groupingBy(WordEntry::getSource))
                .forEach((source, sourceEntries) -> {
                    // 提取领域名称（从 source 或 tags 中）
                    String domainName = extractDomainName(source, sourceEntries.get(0));
                    
                    // 创建或获取 DomainWord
                    DomainWord domainWord = wordModel.getDomainWord(domainName);
                    if (domainWord == null) {
                        domainWord = DomainWord.builder()
                                .domainName(domainName)
                                .build();
                        wordModel.addDomainWord(domainWord);
                    }
                    
                    // 为每个 entry 创建 ExplanationEntry
                    for (WordEntry entry : sourceEntries) {
                        ExplanationEntry explanation = ExplanationEntry.builder()
                                .source(entry.getSource())
                                .detail(entry.getDefinition() != null ? entry.getDefinition() : entry.getTranslation())
                                .type("定义")
                                .language(entry.getLanguage())
                                .priority(entry.getFrequency() != null ? entry.getFrequency() : 0)
                                .confidence(entry.getConfidence() != null ? entry.getConfidence() : 0.5)
                                .build();
                        domainWord.addExplanation(explanation);
                    }
                });
        
        return wordModel;
    }
    
    /**
     * 将 WordModel 转换为 WordEntry 列表
     */
    private List<WordEntry> convertToWordEntries(WordModel wordModel) {
        List<WordEntry> entries = new ArrayList<>();
        
        String primaryWord = wordModel.getPrimaryWord();
        if (primaryWord == null || primaryWord.trim().isEmpty()) {
            return entries;
        }
        
        // 为每个领域创建一个或多个 WordEntry
        if (wordModel.getDomainWords() != null) {
            for (DomainWord domainWord : wordModel.getDomainWords()) {
                String domainName = domainWord.getDomainName();
                
                if (domainWord.getExplanations() != null && !domainWord.getExplanations().isEmpty()) {
                    for (ExplanationEntry explanation : domainWord.getExplanations()) {
                        WordEntry entry = WordEntry.builder()
                                .word(primaryWord)
                                .definition(explanation.getDetail())
                                .language(explanation.getLanguage() != null ? explanation.getLanguage() : wordModel.getLanguage())
                                .partOfSpeech(wordModel.getPartOfSpeech())
                                .source(explanation.getSource() != null ? explanation.getSource() : domainName)
                                .frequency(explanation.getPriority() != null ? explanation.getPriority() : wordModel.getFrequency())
                                .confidence(explanation.getConfidence() != null ? explanation.getConfidence() : wordModel.getConfidence())
                                .tags(List.of(domainName)) // 使用领域名称作为标签
                                .build();
                        entries.add(entry);
                    }
                } else {
                    // 如果没有解释，至少创建一个基本的 entry
                    WordEntry entry = WordEntry.builder()
                            .word(primaryWord)
                            .language(wordModel.getLanguage())
                            .partOfSpeech(wordModel.getPartOfSpeech())
                            .source(domainName)
                            .frequency(wordModel.getFrequency())
                            .confidence(wordModel.getConfidence())
                            .tags(List.of(domainName))
                            .build();
                    entries.add(entry);
                }
            }
        }
        
        // 如果没有领域词，创建一个基本的 entry
        if (entries.isEmpty()) {
            WordEntry entry = WordEntry.builder()
                    .word(primaryWord)
                    .language(wordModel.getLanguage())
                    .partOfSpeech(wordModel.getPartOfSpeech())
                    .source("DomainWordsDict")
                    .frequency(wordModel.getFrequency())
                    .confidence(wordModel.getConfidence())
                    .build();
            entries.add(entry);
        }
        
        return entries;
    }
    
    /**
     * 从 source 或 tags 中提取领域名称
     */
    private String extractDomainName(String source, WordEntry entry) {
        // 首先检查 tags
        if (entry.getTags() != null && !entry.getTags().isEmpty()) {
            return entry.getTags().get(0);
        }
        
        // 从 source 中提取（假设格式为 "领域名称" 或包含领域信息）
        if (source != null && !source.trim().isEmpty()) {
            return source;
        }
        
        return "未知领域";
    }
    
    /**
     * 更新 WordEntry
     */
    private void updateWordEntry(WordEntry existing, WordEntry updated) {
        if (updated.getDefinition() != null) {
            existing.setDefinition(updated.getDefinition());
        }
        if (updated.getTranslation() != null) {
            existing.setTranslation(updated.getTranslation());
        }
        if (updated.getFrequency() != null) {
            existing.setFrequency(updated.getFrequency());
        }
        if (updated.getConfidence() != null) {
            existing.setConfidence(updated.getConfidence());
        }
        if (updated.getTags() != null) {
            existing.setTags(updated.getTags());
        }
    }
}

